import { app, shell, BrowserWindow, ipcMain } from 'electron'
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset'
import os from 'node:os'
import { execSync } from 'node:child_process'
import diskInfo from 'diskinfo'
import si from 'systeminformation'
import physicalCpuCount from 'physical-cpu-count'

function getWindowsId(): string | null {
  try {
    const output = execSync('wmic csproduct get uuid').toString()
    return output.replace('UUID', '').trim()
  } catch {
    return null // 降级处理
  }
}

function getOsVer(ver: string): string {
  const temp = ver.split('.')
  const first = temp?.[0] || ''
  if (Number(first) < 10) {
    return '8'
  } else {
    const third = temp?.[2] || ''
    if (Number(third) < 22000) {
      return '10'
    }
    return '11'
  }
}

const deviceInfo = {
  deviceName: os.hostname(),
  cpuInfo: os.cpus()?.[0]?.model || '',
  uuid: getWindowsId(),
  version: getOsVer(os.release()),
  platform: os.platform() === 'win32' ? 'Windows' : os.platform() === 'darwin' ? 'MacOS' : 'Linux',
  arch:
    process.arch === 'x64' ||
    Object.prototype.hasOwnProperty.call(process.env, 'PROCESSOR_ARCHITEW6432')
      ? '64'
      : '32'
}

interface DiskData {
  blocks: number
  used: number
  available: number
}

function getDiskInfo() {
  const diskData = { blocks: 0, used: 0, available: 0 }
  return (): Promise<DiskData> => {
    if (diskData.blocks) return Promise.resolve(diskData)
    return new Promise((resolve, reject) => {
      diskInfo.getDrives((err, drives) => {
        if (err) {
          reject(err)
          return
        }
        drives.forEach((drive) => {
          diskData.blocks += drive.blocks / 1024 ** 3
          diskData.used += drive.used / 1024 ** 3
          diskData.available += drive.available / 1024 ** 3
        })
        diskData.blocks = getOneFixed(diskData.blocks)
        diskData.used = getOneFixed(diskData.used)
        diskData.available = getOneFixed(diskData.available)
        resolve(diskData)
      })
    })
  }
}

function getCpuUsed(): Promise<number> {
  return new Promise((resolve) => {
    si.currentLoad().then((data) => {
      resolve(Math.round(data.currentLoad * 10) / 10)
    })
  })
}

const getOneFixed = (val: number): number => {
  return Math.floor(val * 10) / 10
}

async function getProcessesList(): Promise<object> {
  const processes = await si.processes()
  const resData = processes.list.map((item) => {
    return {
      cpu: item.cpu,
      mem: item.mem,
      name: item.name,
      memVsz: item.memVsz / 1024,
      memRss: item.memRss / 1024
    }
  })
  return resData
}

function createWindow(): void {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 920,
    height: 630,
    show: false,
    frame: false,
    resizable: false,
    transparent: true,
    autoHideMenuBar: true,
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false
    }
  })

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  mainWindow.webContents.on('did-finish-load', () => {
    mainWindow.webContents.send('get-deviceInfo', deviceInfo)
  })

  // 监听还原窗口
  mainWindow.on('restore', () => {
    mainWindow.webContents.send('restore', 'ok')
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }

  mainWindow.setIcon(icon)

  ipcMain.on('minimize-window', () => mainWindow.minimize())
  ipcMain.on('close-window', () => mainWindow.close())

  const diskFunc = getDiskInfo()
  const logicCpuCount = os.cpus().length
  let diskName = ''
  // 获取硬盘品牌型号
  si.diskLayout()
    .then((data) => {
      data.forEach((disk) => {
        diskName = disk.name
      })
    })
    .catch((err) => console.error(err))

  async function notifyDevice(): Promise<void> {
    const deviceDetail = {
      totalMemory: getOneFixed(os.totalmem() / 1024 ** 3),
      freeMemory: getOneFixed(os.freemem() / 1024 ** 3),
      usedMemory: getOneFixed(os.totalmem() / 1024 ** 3 - os.freemem() / 1024 ** 3),
      usedCpu: await getCpuUsed(),
      totalDisk: (await diskFunc()).blocks,
      freeDisk: (await diskFunc()).available,
      usedDisk: (await diskFunc()).used,
      physicalCpuCount, // 物理核心数
      logicCpuCount, // 逻辑核心数
      diskName: diskName || '', // 硬盘型号
      processList: await getProcessesList()
    }
    // console.log(deviceDetail.memory)
    mainWindow.webContents.send('get-deviceDetail', deviceDetail)
  }
  ipcMain.on('dashboard-finished', () => {
    // 每两秒通知
    notifyDevice()
    setInterval(() => {
      notifyDevice()
    }, 2000)
  })
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  // Set app user model id for windows
  electronApp.setAppUserModelId('com.electron')

  // Default open or close DevTools by F12 in development
  // and ignore CommandOrControl + R in production.
  // see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  createWindow()

  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
